package com.ai.common.http;

import com.ai.common.enums.ConfigModuleEnum;
import com.ai.common.utils.ConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class SmsClient {

    private static final String URL = "http://sdk4report.eucp.b2m.cn:8080/sdkproxy/sendsms.action";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送注册验证码
     * @param phone
     * @param code
     * @return
     */
    public boolean sendRegisterCode(String phone,String code){
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(code)){
            return false;
        }
        String message = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "registrationVerificationCodeMessage");
        if (StringUtils.isBlank(message)){
            return false;
        }
        message = message.replace("code",code);
        return send(phone,message);
    }

    public boolean send(String phone,String message){
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(message)){
            return false;
        }
        //设置请求头参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("cdkey", "6SDK-EMY-6688-KIVOO");
        body.add("password", "237903");
        body.add("phone", phone);
        body.add("message", message);
        //封装请求参数
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body,headers);
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(URL, entity, String.class);
        } catch (RestClientException e) {
            log.error(e.getMessage(),e);
        }
        if (responseEntity != null && StringUtils.isNotBlank(responseEntity.getBody())){
            //System.out.println(responseEntity.getBody());
            //<?xml version="1.0" encoding="UTF-8"?><response><error>0</error><message></message></response>
            if (responseEntity.getBody().contains("<error>0</error>")){
                return true;
            }
        }
        return false;
    }
}
